const {L} = window;
const {BASE_URL} = window.CONFIG;
import {polygonColorMap} from '../../constant/layers';

const service = {
    vec_c: {
        url: 'https://{s}.tianditu.gov.cn/vec_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk={tk}',
    },
    cva_c: {
        url: 'https://{s}.tianditu.gov.cn/cva_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk={tk}',
    },
    img_c: {
        url: 'https://{s}.tianditu.gov.cn/img_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk={tk}',
    },
    cia_c: {
        url: 'https://{s}.tianditu.gov.cn/cia_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk={tk}',
    },
    vec_w: {
        url: 'https://{s}.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk={tk}',
    },
    cva_w: {
        url: 'https://{s}.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk={tk}',
    },
    img_w: {
        url: 'https://{s}.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk={tk}',
    },
    cia_w: {
        url: 'https://{s}.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk={tk}',
    },
    ibo_w: {
        url: 'https://{s}.tianditu.gov.cn/ibo_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ibo&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk={tk}',
    },
    ibo_c: {
        url: 'https://{s}.tianditu.gov.cn/ibo_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ibo&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk={tk}',
    }
};

export function getLayer(alias, token, domains) {
    const { L } = window;
    const name = alias.split('-')[1];
    const id = `base_${alias}_tile`;

    let { url } = service[name];

    url = url.replace('{tk}', token);

    const layer = L.tileLayer(url, {
        id,
        minZoom: 2,
        maxZoom: 18,
        maxNativeZoom: 18,
        subdomains: domains.split(',')
    });

    return layer;
}

export function getMapTypes(type, name, projection) {
    const mapTypes = [`map-${type}_${projection}`];

    if (name) {
        if (type === 'img' || type === 'ter') {
            const borderName = type.charAt(0) + 'bo';
            mapTypes.push(`bou-${borderName}_${projection}`);
        }
        const noteName = name.charAt(0) + type.charAt(0) + 'a';
        mapTypes.push(`note-${noteName}_${projection}`);
    }
    return mapTypes;
}

export function getLayers(params) {
    const layers = [];
    const { type, projection, name, domains, token } = params;

    const mapTypes = getMapTypes(type, name, projection);

    mapTypes.forEach(mapType => {
        const layer = getLayer(mapType, token, domains);
        if (layer) {
            layers.push(layer);
        }
    });

    return layers;
}

export function updateLayerGroup(layerGroup, layers, type="base") {
    const existLayers = layerGroup.getLayers();
    let baseLayers = [];
    if (type === 'base') {
        baseLayers = existLayers.filter(existLayer => {
            return existLayer.options.id.startsWith('base_');
        });
    } else {
        baseLayers = existLayers.filter(existLayer => {
            return existLayer.options.id.startsWith('service_');
        });
    }

    // 添加新图层
    layers.forEach(layer => {
        const index = baseLayers.findIndex(baseLayer => {
            return baseLayer.options.id === layer.options.id;
        });
        if (index < 0 && layer.options.id) {
            layerGroup.addLayer(layer);
        }
    });

    // 移除旧图层
    baseLayers.forEach(baseLayer => {
        const index = layers.findIndex(layer => {
            return layer.options.id === baseLayer.options.id;
        });
        if (index < 0) {
            layerGroup.removeLayer(baseLayer);
        }
    })

    // 图层排序
    sortLayers(layerGroup);
}

// 显示、隐藏图层
export function hideOrShowLayer(layerGroup, key, type) {
    layerGroup.eachLayer(layer => {
        const {id} = layer.options;
        if (id === key) {
            if (type === 'hide') {
                layer.setOpacity(0);
            } else {
                layer.setOpacity(1);
            }
        }
    });
}

// 图层排序
export function sortLayers(layerGroup) {
    let num = 0;
    const layers = layerGroup.getLayers();
    const length = layers.length;
    layers.forEach((layer, index) => {
        const layerId = layer.options.id;
        if (layerId.startsWith('base_map')) {
            layer.setZIndex(0);
        }
        if (layerId.startsWith('base_note')) {
            layer.setZIndex(length - 1);
            num += 1;
        }
        if (layerId.startsWith('base_bou')) {
            layer.setZIndex(length - 2);
            num += 1;
        }
        if (layerId.startsWith('service_')) {
            layer.setZIndex(index - num === 0? 1 : index-num);

        }
    })
}

/**
 * 添加点图层
 * @param {*} map 
 * @param {*} data 
 * @param {*} layerName 
 */
export function addPointLayer(map, data, layerName) {
    if(!map) return null;
    let pointIcon = L.icon({
        iconUrl: `${BASE_URL}/images/${layerName}.png`,
        iconSize:[26,26],
        iconAnchor: [12,12]
    });

    const layer = L.geoJSON(data, {   
        pointToLayer: function (feature, latlng){
            return L.marker(latlng, {
                icon: pointIcon
            });
        }
    });
    return layer;
}

/**
 * 添加面图层
 * @param {*} map 
 * @param {*} data 
 * @param {*} layerName 
 */
export function addPolygonLayer(map, data, layerName){
    if(!map) return;
    
    let polygonLayer = L.geoJSON(data, {
        style: function (feature) {
            return polygonColorMap[layerName][feature.properties.classify];
            // switch (feature.properties.classify) {
            //     case 'Republican':
            //         return {
            //             color: "#ff0000"
            //         };
            //     case 'Democrat':
            //         return {
            //             color: "#0000ff"
            //         };
            // }
        }
    }).addTo(map);

    return polygonLayer;
}

/**
 * 墨卡托转经纬度
 * @param {*} mercator 
 * @returns 
 */
export function mercatorToLnglat(mercator){
    let lnglat = {lng:0, lat:0};

    let x = mercator.x / 20037508.34 * 180;
    let y = mercator.y / 20037508.34 * 180;

    y = 180/Math.PI*(2*Math.atan(Math.exp(y*Math.PI/180)) - Math.PI/2);

    lnglat.lng = x;
    lnglat.lat = y;

    return lnglat;
}

/**
 * 经纬度转墨卡托
 * @param {*} lnglat 
 * @returns 
 */
export function lnglatToMercator(lnglat){
    let mercator ={};

    let x = lnglat.lng * 20037508.34 / 180;
    let y = Math.log(Math.tan((90 + lnglat.lat) * Math.PI/360)) / (Math.PI / 180);

    y=y * 20037508.34 / 180;
    
    mercator.x = x;
    mercator.y = y;

    return mercator;
}

export function getfieldsLayer (layerFields={}) {
    let fieldsLayer = {};
    Object.keys(layerFields).forEach(key => {
        fieldsLayer[layerFields[key]] = key;
    });
    return fieldsLayer;
}

